/*
* @file bsp_i2s.cpp
* @brief This file contains the implementation of the BSP_I2S class
* @author feiniao
* @date 2025-5-07
* @version 1.0
* @note This code is designed to work with ESP32-S3 and uses the ESP-IDF 5.2.3 framework.
*/


#include "bsp_i2s.h"


/*
* @brief Constructor for the BSP_I2S class
*        Initializes the I2S driver with the specified configuration
* @param bck_io_num GPIO number for the BCK pin
* @param ws_io_num GPIO number for the WS pin
* @param data_in_num GPIO number for the DATA pin
*/
BSP_I2S::BSP_I2S(int bck_io_num, int ws_io_num, int data_in_num, int data_out_num, uint32_t sample_rate, i2s_port_t i2s_port, i2s_mode_t i2s_mode, i2s_bits_per_sample_t bits_per_sample) 
: bck_io_num(bck_io_num), ws_io_num(ws_io_num), data_in_num(data_in_num), data_out_num(data_out_num), sample_rate(sample_rate), i2s_port(i2s_port), i2s_mode(i2s_mode), bits_per_sample(bits_per_sample)
{
    i2s_config_t i2s_config = {
        .mode = i2s_mode,
        .sample_rate = sample_rate,
        .bits_per_sample = bits_per_sample,
        .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
        .communication_format = I2S_COMM_FORMAT_STAND_I2S,
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // default interrupt priority
        .dma_buf_count = 4, // number of buffers
        .dma_buf_len = 1024,   // size of each buffer in bytes
        .use_apll = false
    };

    i2s_pin_config_t pin_config = {
        .bck_io_num = bck_io_num,
        .ws_io_num = ws_io_num,
        .data_out_num = data_out_num,
        .data_in_num = data_in_num
    };

    i2s_driver_install(i2s_port, &i2s_config, 0, NULL);
    i2s_set_pin(i2s_port, &pin_config);
}


/*
* @brief Destructor for the BSP_I2S class
*        Uninstalls the I2S driver
*/
BSP_I2S::~BSP_I2S()
{
    i2s_driver_uninstall(i2s_port);
    gpio_reset_pin((gpio_num_t)bck_io_num);
    if (data_in_num != -1) gpio_reset_pin((gpio_num_t)data_in_num);
    gpio_reset_pin((gpio_num_t)ws_io_num);
    if (data_out_num != -1) gpio_reset_pin((gpio_num_t)data_out_num);
}


/*
* @brief Reads a sample from the I2S interface
* @return The 32-bit sample read from the I2S interface
*/
int32_t BSP_I2S::int32t_read()
{
    uint32_t data;
    size_t bytes_read;
    i2s_read(i2s_port, &data, sizeof(uint32_t), &bytes_read, portMAX_DELAY);
    // 右移8位获取24位数据（符号自动扩展）
    int32_t sample = data >> 8;
    if(sample & 0x00800000)    sample |= 0xFF000000;
    return sample;
}


/*
* @brief Reads a primordial sample from the I2S interface
* @return The 32-bit sample read from the I2S interface
*/
int16_t BSP_I2S::int16t_read() {
    int16_t data;
    size_t bytes_read;
    i2s_read(i2s_port, &data, sizeof(int16_t), &bytes_read, portMAX_DELAY);
    return data;
}


esp_err_t BSP_I2S::write(const void* buffer, size_t bytes_to_write)
{
    size_t bytes_written;
    return i2s_write(i2s_port, buffer, bytes_to_write, &bytes_written, portMAX_DELAY);
}
